"""
verify create agent with knowledge API - required parameters validation
test workspace_id and source_agent_id are required
"""
import sys
from pathlib import Path

# Add project root to Python path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

import logging
from src.llm.hiagent_app.services.agent_knowledge_service import AgentKnowledgeService
from src.llm.hiagent_app.config.hiagent_config import HiAgentConfig

# configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def test_missing_workspace_id():
    """test that missing workspace_id raises ValueError"""
    logger.info("=" * 60)
    logger.info("Test 1: Missing workspace_id should raise ValueError")
    logger.info("=" * 60)

    service = AgentKnowledgeService()
    source_agent_id = "d3tjsrvi96maquv5k8v0"

    try:
        agent_id, knowledge_id = service.create_agent_with_knowledge(
            agent_name="test_agent",
            knowledge_name="test_knowledge",
            workspace_id=None,  # Missing
            source_agent_id=source_agent_id
        )
        logger.error("FAILED - Should have raised ValueError for missing workspace_id")
        return False
    except ValueError as e:
        if "workspace_id" in str(e):
            logger.info(f"SUCCESS - ValueError raised as expected: {str(e)}")
            return True
        else:
            logger.error(f"FAILED - Wrong error message: {str(e)}")
            return False
    except Exception as e:
        logger.error(f"FAILED - Wrong exception type: {type(e).__name__}: {str(e)}")
        return False


def test_missing_source_agent_id():
    """test that missing source_agent_id raises ValueError"""
    logger.info("\n" + "=" * 60)
    logger.info("Test 2: Missing source_agent_id should raise ValueError")
    logger.info("=" * 60)

    service = AgentKnowledgeService()
    workspace_id = HiAgentConfig.DEFAULT_WORKSPACE_ID

    try:
        agent_id, knowledge_id = service.create_agent_with_knowledge(
            agent_name="test_agent",
            knowledge_name="test_knowledge",
            workspace_id=workspace_id,
            source_agent_id=None  # Missing
        )
        logger.error("FAILED - Should have raised ValueError for missing source_agent_id")
        return False
    except ValueError as e:
        if "source_agent_id" in str(e):
            logger.info(f"SUCCESS - ValueError raised as expected: {str(e)}")
            return True
        else:
            logger.error(f"FAILED - Wrong error message: {str(e)}")
            return False
    except Exception as e:
        logger.error(f"FAILED - Wrong exception type: {type(e).__name__}: {str(e)}")
        return False


def test_missing_both_parameters():
    """test that missing both parameters raises ValueError"""
    logger.info("\n" + "=" * 60)
    logger.info("Test 3: Missing both workspace_id and source_agent_id")
    logger.info("=" * 60)

    service = AgentKnowledgeService()

    try:
        agent_id, knowledge_id = service.create_agent_with_knowledge(
            agent_name="test_agent",
            knowledge_name="test_knowledge",
            workspace_id=None,  # Missing
            source_agent_id=None  # Missing
        )
        logger.error("FAILED - Should have raised ValueError")
        return False
    except ValueError as e:
        logger.info(f"SUCCESS - ValueError raised as expected: {str(e)}")
        return True
    except Exception as e:
        logger.error(f"FAILED - Wrong exception type: {type(e).__name__}: {str(e)}")
        return False


def test_with_both_parameters():
    """test successful creation with both required parameters"""
    logger.info("\n" + "=" * 60)
    logger.info("Test 4: With both required parameters (should succeed)")
    logger.info("=" * 60)

    service = AgentKnowledgeService()
    workspace_id = HiAgentConfig.DEFAULT_WORKSPACE_ID
    source_agent_id = "d3tjsrvi96maquv5k8v0"

    try:
        agent_id, knowledge_id = service.create_agent_with_knowledge(
            agent_name="test_agent_valid",
            knowledge_name="test_knowledge_valid",
            workspace_id=workspace_id,
            source_agent_id=source_agent_id
        )
        logger.info(f"SUCCESS - Agent ID: {agent_id}, Knowledge ID: {knowledge_id}")

        # cleanup
        logger.info("Cleaning up test resources...")
        service._cleanup_resources(agent_id, knowledge_id, workspace_id)
        return True
    except Exception as e:
        logger.error(f"FAILED - Error: {str(e)}")
        logger.error("NOTE: If error mentions config incomplete, make sure source agent is properly configured")
        return False


def test_api_request_model_validation():
    """test API request model requires both parameters"""
    logger.info("\n" + "=" * 60)
    logger.info("Test 5: API request model validation")
    logger.info("=" * 60)

    try:
        from src.routers.hiagent_center import CreateAgentWithKnowledgeRequest
        from pydantic import ValidationError

        # Test missing workspace_id
        try:
            request = CreateAgentWithKnowledgeRequest(
                agent_name="test",
                source_agent_id="d3tjsrvi96maquv5k8v0"
                # Missing workspace_id
            )
            logger.error("FAILED - Should have raised ValidationError for missing workspace_id")
            return False
        except ValidationError as e:
            logger.info(f"SUCCESS - ValidationError raised for missing workspace_id")

        # Test missing source_agent_id
        try:
            request = CreateAgentWithKnowledgeRequest(
                agent_name="test",
                workspace_id="test_ws"
                # Missing source_agent_id
            )
            logger.error("FAILED - Should have raised ValidationError for missing source_agent_id")
            return False
        except ValidationError as e:
            logger.info(f"SUCCESS - ValidationError raised for missing source_agent_id")

        # Test with both parameters
        request = CreateAgentWithKnowledgeRequest(
            agent_name="test",
            workspace_id="test_ws",
            source_agent_id="test_source"
        )
        logger.info(f"SUCCESS - Request model created with both required parameters")

        return True
    except Exception as e:
        logger.error(f"FAILED - Error: {str(e)}")
        return False


def main():
    """main test function"""
    logger.info("Starting required parameters validation tests")
    logger.info("=" * 60)

    results = {
        "test_api_request_model_validation": test_api_request_model_validation(),
        "test_missing_workspace_id": test_missing_workspace_id(),
        "test_missing_source_agent_id": test_missing_source_agent_id(),
        "test_missing_both_parameters": test_missing_both_parameters(),
        "test_with_both_parameters": test_with_both_parameters()
    }

    logger.info("\n" + "=" * 60)
    logger.info("Test Results Summary")
    logger.info("=" * 60)
    for test_name, result in results.items():
        status = "PASS" if result else "FAIL"
        logger.info(f"{test_name}: {status}")

    all_passed = all(results.values())

    logger.info("\n" + "=" * 60)
    if all_passed:
        logger.info("ALL TESTS PASSED")
        logger.info("=" * 60)
        logger.info("Required parameters validation is working correctly:")
        logger.info("1. workspace_id is required - raises ValueError when missing")
        logger.info("2. source_agent_id is required - raises ValueError when missing")
        logger.info("3. API request model enforces required parameters")
        logger.info("4. With both parameters, agent creation succeeds")
    else:
        logger.info("SOME TESTS FAILED")
        logger.info("=" * 60)
        logger.info("Please review the error messages above")


if __name__ == "__main__":
    main()
